/*
 * All rights Reserved, Designed By Yealink
 * Copyright (c) 2017/12/25 by Yealink
 *
 * @author yl1633
 * Createdate:  2017/12/25 11:33
 */
package com.xx.login_required.annotation;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * @author fanjj
 * @date 2017/12/25
 */
public class LoginRequiredInterceptor extends HandlerInterceptorAdapter {
    private static Logger logger = LoggerFactory.getLogger(LoginRequiredInterceptor.class);

    public LoginRequiredInterceptor() {
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            if (handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                Method method = handlerMethod.getMethod();
                LoginRequired annotation = method.getAnnotation(LoginRequired.class);
                if (annotation == null) {
                    annotation = handlerMethod.getBeanType().getAnnotation(LoginRequired.class);
                }
                if (annotation != null && annotation.enable()) {//使用注解
                    int a = 2;
                    if (a == 1) {
                        loginError(request, response);//需求登录
                        return false;
                    }
                    if (StringUtils.isNotBlank(annotation.permission()) && !annotation.permission().equals("1")) {
                        permissionError(request, response);//需求权限
                        return false;
                    }
                }
            }
            return super.preHandle(request, response, handler);
        } catch (Exception e) {
            logger.error("LoginRequiredInterceptor preHandle ERROR: {}", e.getMessage(), e);
            return false;
        }
    }

    private void loginError(HttpServletRequest request, HttpServletResponse response) {
        if (isAjaxRequest(request)) {
            PrintWriter writer = null;
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            try {
                writer = response.getWriter();
                writer.print("需要登录");
            } catch (IOException e) {
                logger.error("redirectToLoginPage error", e);
            } finally {
                if (writer != null)
                    writer.close();
            }
        } else {
            response.setStatus(302);
            response.setHeader("location", request.getContextPath() + "/index.jsp");
        }
    }

    private void permissionError(HttpServletRequest request, HttpServletResponse response) {
        if (isAjaxRequest(request)) {
            PrintWriter writer = null;
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html; charset=utf-8");
            try {
                writer = response.getWriter();
                writer.print("需要权限");
            } catch (IOException e) {
                logger.error("redirectToLoginPage error", e);
            } finally {
                if (writer != null)
                    writer.close();
            }
        } else {
            response.setStatus(302);
            response.setHeader("location", request.getContextPath() + "/401.jsp");
        }
    }

    private boolean isAjaxRequest(HttpServletRequest httpServletRequest) {
        boolean result = false;
        if (httpServletRequest.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(httpServletRequest.getHeader("X-Requested-With"))) {
            result = true;
        }
        return result;
    }
}